var fs = require("fs");
var mammoth = require("mammoth");
var express = require("express");
var path = require('path');
const formidable = require('formidable')
var async = require('async'); 
var minify = require('html-minifier').minify;
var proxy = require('http-proxy-middleware');

var app = express()
var bodyParser = require('body-parser')

let domain = '127.0.0.1'
let port = '2020'

app.all('*', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header('X-Powered-By', ' 3.2.1')
    next()
})

app.use('/', express.static(path.join(__dirname, '..', 'dist')));

var server = app.listen(port, domain, function () {
    var host = server.address().address
    var port = server.address().port
    console.log("访问地址为 http://%s:%s", host, port)
})

var apiProxy = proxy('/common',  {
    target: 'http://101.132.134.132:8080',
    changeOrigin: true,
    onProxyReq: (proxyReq, req, res, option) => {
        if (proxyReq.getHeader("origin")) {
            proxyReq.setHeader("origin", 'http://101.132.134.132:8080');
        }
    }
});
app.use(apiProxy);

app.use(bodyParser.json()) // for parsing application/json
app.use(bodyParser.urlencoded({ extended: false })) // for parsing application/x-www-form-urlencoded

// app.use('/common/uploadhtml', proxy({
//     // 代理跨域目标接口
//     target: 'http://101.132.134.132:8080',
//     changeOrigin: true
// }));

app.post('/minify', function (req, res) {
    // console.log(req)
    let content = minify(req.body.content,{quoteCharacter: '"',collapseWhitespace:true,removeEmptyElements:true,removeEmptyAttributes:true,minifyJS:true,minifyCSS:true})
    res.json(content)
})

app.post('/createFile', function (req, res) {
    fs.writeFile(req.body.path + '/temp.txt', minify(req.body.content,{quoteCharacter: "'",collapseWhitespace: true,minifyJS:true, minifyCSS:true}),function(err) {
        if (err) {
            return console.error(err);
        }
        res.json('保存成功！')
    });
})

app.post('/chooseFile', function (req, res) {
    const os = require('os')
    const userInfo = os.userInfo()
    let path = userInfo.homedir + '/Documents' +req.body.path;
    fs.readdir(path,function(err, files){
        if (err) {
            return console.error(err);
        }
        let directory = []
        async.eachSeries(files, function(file, callback) {
            // console.log(file)
            fs.stat(path + '/' + file, function(err, stats){
                if(stats.isDirectory()) directory.push(file)
                callback(err)
            })  
        }, function(err) {
            // console.log(directory)
            res.json({
                homedir: userInfo.homedir + '/Documents',
                directory: directory
            })
        })
     });
})

app.post('/upload', function (req, res) {
    // console.log(req)
    var form = new formidable.IncomingForm()
    form.keepExtensions = true
    form.multiples = true
    // console.log(req)
    form.parse(req, function (err, fileds, files) {
        if (err) {
            return err
        } else {
            // console.log(files)
            const objectKey = new Date().getTime() + '.' + files.file.name.split('.').pop();
            uploadFile(objectKey, files.file.path).then(result => {
                // console.log(result)
                let url = result.url.replace('http://dw-pro.oss-cn-shanghai.aliyuncs.com', 'https://v.iduov.com')
                res.end(JSON.stringify({location: url}))
            })
        }
    })
})

app.post('/word-to-html', function (req, res) {
    var form = new formidable.IncomingForm()
    form.keepExtensions = true
    form.multiples = true
    form.parse(req, function (err, fileds, files) {
        if (err) {
            return err
        } else {
            // console.log(files.file.path.split('.').pop())
            if (files.file.path.split('.').pop() === 'docx') {
                var options = {
                    styleMap: [
                        "p[style-name^='Heading'] => p:fresh > b:fresh"
                    ],
                    convertImage: mammoth.images.imgElement(function (image) {
                        return image.read("base64").then(function (imageBuffer) {
                            // arrayBuffer转Buffer
                            const buffer = Buffer.from(imageBuffer, 'base64');
                            const objectKey = new Date().getTime() + '.' + image.contentType.split('/').pop();
                            return uploadFile(objectKey, buffer).then((result) => {
                                let url = result.url.replace('http://dw-pro.oss-cn-shanghai.aliyuncs.com', 'https://v.iduov.com')
                                return {
                                    src: url,
                                    alt: "插图",
                                    width: "100%"
                                };
                            })
                        });
                    })
                };
    
                mammoth.convertToHtml({ path: files.file.path }, options)
                    .then(function (result) {
                        var html = result.value; // The generated HTML
                        var messages = result.messages; // Any messages, such as warnings during conversion
                        // console.log(html)
                        res.json(html)
                    })
                    .done();
            } else {
                res.json('目前只支持.docx转换')
            }
        }
    })
})

function uploadFile (objectKey, buffer) {
    let OSS = require('ali-oss')
    // 配置
    const client = new OSS({
        region: 'oss-cn-shanghai',
        accessKeyId: 'LTAIAQDZJdw2EcuI',
        accessKeySecret: 'HikkfZrilW2vQTE6boWarQIxXGNG6B',
        bucket: 'dw-pro'
    });
    // 文件名
    objectKey = 'reader/articleDetail/' + formatTimeTwo(new Date().getTime(), 'Y-M-D') + '/' + objectKey;

    // 上传
    return client.put(objectKey, buffer).then(function (result) {
        // console.log(result.url)
        return Promise.resolve(result)
    }).catch(function (err) {
        console.log(err);
    });
}

function formatTimeTwo(number, format) {
    var formateArr = ['Y', 'M', 'D', 'h', 'm', 's']
    var returnArr = []
    // format = 'Y-M-D-h-m'
    // var date = new Date(number * 1000);
    var date = new Date(number)
    returnArr.push(date.getFullYear())
    returnArr.push(formatNumber(date.getMonth() + 1))
    returnArr.push(formatNumber(date.getDate()))
    returnArr.push(formatNumber(date.getHours()))
    returnArr.push(formatNumber(date.getMinutes()))
    returnArr.push(formatNumber(date.getSeconds()))
    for (var i in returnArr) {
        format = format.replace(formateArr[i], returnArr[i])
    }
    return format
}

// 将数字转换成两位数格式，个位数时在前面补0
function formatNumber(n) {
    n = n.toString()
    return n[1] ? n : '0' + n
}